#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import sys
import time
from datetime import datetime

import requests


class DingtalkRobot(object):
    '''
    将统计结果发送给钉钉
    '''

    def send_msg_to_dd(self, web_hook_url: str, title: str, mk_text: str) -> None:
        '''
        发送mk_text到钉钉
        @param web_hook_url: 机器人链接  str
        @param title: 主题名  str
        @param mk_text: 钉钉内容  str
        @return: None
        '''

        msg_body = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": mk_text
            },
        }
        headers = {
            "Content-Type": "application/json;charset=utf-8"
        }
        retry_count = 0
        while retry_count < 10:
            try:
                response = requests.post(url=web_hook_url, data=json.dumps(msg_body), headers=headers, verify=False)
                if response.status_code == 200:
                    print("{} 发送钉钉信息成功：{}\n".format(datetime.now(), response.status_code))
                    break
                else:
                    print("{}  返回状态码不正常：{}\n".format(datetime.now(), response.status_code))
            except Exception as e:
                print("{}  请求异常：{}\n".format(datetime.now(), e))
                retry_count += 1
                time.sleep(2)

    def main(self, mk_text: str, title='stepn',
             web_hook_url='https://oapi.dingtalk.com/robot/send?access_token=3c7461401531f7c75b9210605b1e648e26b685c65a24617edcbfa631ccf81358')-> None:
        '''
        暴露给外部使用，进行机器人发送
        @param web_hook_url:
        @param title:
        @param mk_text:
        @return:
        '''
        self.send_msg_to_dd(web_hook_url, title, mk_text)
